package LocalCRM::Doc;

use base 'LocalCRM';
use LocalCRM::DBI::Invoice;
use PDF::API2;
use Data::Dumper;
use strict;

sub new
{
    my $self = shift->SUPER::new();

    $self->{pdf} = new PDF::API2;
    $self->{_db} = new LocalCRM::DBI::Invoice;

    $self->{font} =
    {
	'Arial'		=> $self->{pdf}->corefont('Arial',-encode=>'cp1251'),
	'Times'		=> $self->{pdf}->corefont('Times-Roman',-encode=>'cp1251'),
	'TimesB'	=> $self->{pdf}->corefont('Times-Bold',-encode=>'cp1251'),
	'Verdana'	=> $self->{pdf}->corefont('Verdana',-encode=>'cp1251'),
	'VerdanaB'	=> $self->{pdf}->corefont('Verdana,Bold',-encode=>'cp1251'),
	'Courier'	=> $self->{pdf}->corefont('Courier-Bold',-encode=>'cp1251'),
    };

    $self->{month} =
    {
	'rod'	=>
	{
	    1	=> 'января',
	    2	=> 'февраля',
	    3	=> 'марта',
	    4	=> 'апреля',
	    5	=> 'мая',
	    6	=> 'июня',
	    7	=> 'июля',
	    8	=> 'августа',
	    9	=> 'сентября',
	    10	=> 'октября',
	    11	=> 'ноября',
	    12	=> 'декабря',
	}
    };

    return $self;
}

sub id
{
    my $self = shift;

    if ( $self->{_id} = $_[0] )
    {
	unless ( $self->{invoice} = $self->{_db}->getById($self->{_id}) )
	{
	    die sprintf 'Document with id#%d not found in database!', $self->{_id}
	}

	@{$self->{data}->{db}} = $self->{_db}->getItemsByInvoiceId($self->{_id});
    }

    return $self;
}

sub save
{
    my $self = shift;

    if ( $self->{_id} )
    {
	if ( my $filename = $self->filename($_[0]) )
	{
	    unless ( -d(sprintf '%s/%04d',$self->{_cfg}->val('Path','files'), $self->{invoice}->{account_id}) ) { mkdir(sprintf '%s/%04d',$self->{_cfg}->val('Path','files'), $self->{invoice}->{account_id}); }
	    unless ( -d(sprintf '%s/%04d/invoice',$self->{_cfg}->val('Path','files'), $self->{invoice}->{account_id}) ) { mkdir(sprintf '%s/%04d/invoice',$self->{_cfg}->val('Path','files'), $self->{invoice}->{account_id}); }

	    $self->{pdf}->saveas( sprintf '%s/%04d/invoice/%s', $self->{_cfg}->val('Path','files'), $self->{invoice}->{account_id}, $filename );

	    return $filename;
	}
    }
}

sub filename
{
    my $self = shift;
    my $ext  = $_[0]||'pdf';
    my ($class) = (ref $self) =~ /localcrm::doc::(.+)/i;

    if ( $class )
    {
	my $contract = $self->{invoice}->{contract_number};
	$contract =~ s/[^\w\d]/\_/g;

	return sprintf '%02d%02d%s_%d_%s.%s', $self->{invoice}->{date}->yr(), $self->{invoice}->{date}->mon(), $contract, $self->{_id}, lc($class), $ext;
    }
}

sub output	{ shift->{pdf}->stringify(); }

1;
